const app = getApp()
var qCloud = require("../../index.js");
var timerInterval = null;

Page({
    /**
     * 页面的初始数据
     */
    data: {
        imgPath: qCloud.config.STATIC_IMAGE_PATH,
        remember: false,
        phone: "",
        password: "",
        code: "",

        codeDisabled: false,
        codeText: "获取验证码",
        countDown: 60,
        maxTime: 60,
        loginType: '1', // 登录类型， 1=账户密码登录，2：短信验证码登录，3：第三方授权登录，4：客户端授权登录

        showPrivacy: false
    },

    onLoad: function (options) {
        let self = this;
        // wx.getPrivacySetting({
        //   success: res => {
        //     console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        //     if (res.needAuthorization) {
        //       // 需要弹出隐私协议
        //       this.setData({
        //         showPrivacy: true
        //       })
        //     } else {
        //       console.log("=============" + getPrivacySetting)
        //       // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
        //       // wx.getUserProfile()
        //       // wx.chooseMedia()
        //       // wx.getClipboardData()
        //       // wx.startRecord()
        //     }
        //   },
        //   fail: () => {},
        //   complete: () => {}
        // })

      
        let remember = wx.getStorageSync("weapp_remember_flag");
        if (remember) {
            self.setData({
                remember: remember
            })

            let userName = wx.getStorageSync("weapp_remember_userName");
            if (userName) {
                self.setData({
                    phone: qCloud.crypto.decrypt(userName)
                })
            }

            let password = wx.getStorageSync("weapp_remember_password");
            if (password) {
                self.setData({
                    password: qCloud.crypto.decrypt(password)
                })
            }
        }
    },
  

    rememberTap() {
        this.setData({
            remember: !this.data.remember
        });
    },

    // 监听输入手机号
    phoneInput(e) {
        this.setData({
            phone: e.detail.value
        })
    },

    // 监听输入密码
    passwordInput(e) {
        this.setData({
            password: e.detail.value
        })
    },

    bindSendCodeClick() {
        let self = this;
        if (self.data.phone == "") {
            wx.showToast({
                title: "请输入手机号码",
                icon: "error"
            })
            return;
        }
        let params = {
            type: "0",
            phone: qCloud.crypto.encrypt(self.data.phone)
        };

        // 发送验证码
        app.fetchNoTokenApis(self, qCloud.api.smsCode, params, "POST", function (e) {
            if (e.data.code != 200) {
                self.data.codeDisabled = false
                if (timerInterval) {
                    clearTimeout(timerInterval);
                }
                wx.showModal({
                    content: e.data.msg
                });
            } else {
                self.data.codeText = self.data.maxTime + "s后重试";
                self.data.codeDisabled = true;
                timerInterval = setTimeout(self.refreshCode, 1000);
            }
        })
    },

    refreshCode: function () {
        let self = this;
        if (self.data.countDown > 0) {
            self.setData({
                codeDisabled: true,
                codeText: self.data.countDown + "s后重试",
                countDown: self.data.countDown - 1
            })
            timerInterval = setTimeout(self.refreshCode, 1000);
        } else {
            self.setData({
                codeDisabled: false,
                codeText: "重新获取",
                countDown: self.data.maxTime
            })
            if (timerInterval) {
                clearTimeout(timerInterval);
            }
        }
    },

    codeInput: function (e) {
        this.data.code = e.detail.value;
    },

    /**
     * 登录方式
     */
    chooseLoginType(e) {
        let self = this
        self.setData({
            loginType: e.currentTarget.dataset.role
        })
    },

    bindClickLogin() {
        let self = this;
        if (self.data.phone == "") {
            wx.showToast({
                title: "请输入手机号码",
                icon: "error"
            })
            return;
        }

        if (self.data.loginType == '2') {
            if (self.data.code == "") {
                wx.showToast({
                    title: "请输入短信验证码",
                    icon: "error"
                })
                return;
            }
        }

        if (self.data.loginType == '1') {
            if (self.data.password == "") {
                wx.showToast({
                    title: "请输入登录密码",
                    icon: "error"
                })
                return;
            }
        }

        // 记住账户密码
        if (self.data.remember) {
            wx.setStorageSync("weapp_remember_flag", self.data.remember)
            wx.setStorageSync("weapp_remember_userName", qCloud.crypto.encrypt(self.data.phone))
            wx.setStorageSync("weapp_remember_password", qCloud.crypto.encrypt(self.data.password))
        } else {
            wx.removeStorageSync("weapp_remember_flag")
            wx.removeStorageSync("weapp_remember_userName")
            wx.removeStorageSync("weapp_remember_password")
        }

        let params = {};
        if (self.data.loginType == '1') {
            params = {
                userName: qCloud.crypto.encrypt(self.data.phone),
                password: qCloud.crypto.encrypt(self.data.password),
                loginType: self.data.loginType,
                encryptType: "1"
            }
        } else {
            params = {
                userName: qCloud.crypto.encrypt(this.data.phone),
                code: this.data.code,
                loginType: self.data.loginType,
                encryptType: "1"
            }
        }

        qCloud.login({
            method: "POST",
            data: params,
            success: function (result) {
                if (result.code == 200) {
                    app.fetchApis(self, qCloud.api.getInfo, {}, "GET", function (e) {
                        if (e.data.code == 200) {
                            qCloud.session.setPermi(e.data.permissions);
                            qCloud.session.setRole(e.data.role);
                            qCloud.session.setUser(e.data.user);

                            wx.reLaunch({
                                url: "/pages/index/index",
                            });
                        } else {
                            qCloud.session.clear();
                        }
                    });
                } else {
                    qCloud.session.clear();
                    wx.showToast({
                        title: result.msg,
                        icon: "error"
                    });
                }
            },
            fail: function (error) {
                qCloud.session.clear();
                wx.showToast({
                    title: error.msg,
                    icon: "error"
                });
            }
        });
    },

    register: function () {
        wx.navigateTo({
            url: "/pages/register/register",
        })
    },

    forgotPassword: function () {
        wx.navigateTo({
            url: "/pages/login/forgot",
        })
    }
})
